from rest_framework import serializers
from study.models import Student, Classes
# 序列化器
#class StudentSerializer(serializers.Serializer):  # abc.ABC
#    # 返回字段数据和数据的校验
#    id = serializers.IntegerField(label='ID', read_only=True)  # read_only=True只读
#    name = serializers.CharField(max_length=20, label='姓名')  # label对应的是前端
#    age = serializers.IntegerField(label='年龄', required=False)  # required=False非必填字段
#    sex = serializers.IntegerField(label='性别')
#    c_time = serializers.DateTimeField(label='创建时间')
#    u_time = serializers.DateTimeField(label='修改时间')
#    is_delete = serializers.BooleanField(label='逻辑删除')


# 优化
class StudentSerializer(serializers.ModelSerializer):
    # 自定义字段，添加新字段
    # 了解即可，一般不用此方法，因为他会覆盖原字段
    # classes = serializers.StringRelatedField(read_only=True)

    # 注意一定不能和原字段重名，否则会覆盖
    class_name = serializers.CharField(read_only=True, source='classes.name')
    class Meta:
        model = Student
        fields = '__all__'
    # 自定义校验，年龄0到200间，从原模型增加额外参数extra_kwargs
        extra_kwargs = {
            'age': {
                'min_value': 0,
                'max_value': 200
            }
        }
    # 自定义检验，对指定属性值进行校验
    #def validate_name(self, value):
    #    if 'python' not in value.lower():
    #        raise serializers.ValidationError('name error')
    #   return value
    # 自定义校验，获取所有属性值
    #def validate(self, attrs):
    #    if 'python' not in attrs['name'].lower():
    #        raise serializers.ValidationError('name error')
    #    return attrs


class SimpleStudentSerialiizer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['id', 'name']


class ClassesSerializer(serializers.ModelSerializer):
    # 自定义字段
    student_set = SimpleStudentSerialiizer(read_only=True, many=True)
    class Meta:
        model = Classes
        fields = '__all__'

    # 自定义name的校验
    def validate_name(self, value):
        if 'python' not in value:
            raise serializers.ValidationError('班级名必带python')
        return value